package cn.edu.cuit.elena.transaction.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import cn.edu.cuit.elena.db.DataSource;
import cn.edu.cuit.elena.db.Schema;
import cn.edu.cuit.elena.db.Schema.Table;
import cn.edu.cuit.elena.nati.shell.HiveShell;
import cn.edu.cuit.elena.transaction.system.UserContext;

public class Hive
{
    private static Map<String, Hive> controllers;

    private UserContext userContext;
    private DataSource dataSource;

    static
    {
        controllers = new HashMap<String, Hive>();
    }

    private Hive(UserContext userContext, DataSource dataSource)
    {
        this.userContext = userContext;
        this.dataSource = dataSource;
    }

    /**
     * Get Hive object for each user and a specified datasource. One Hive object subjects to one
     * user, additionally, each user must owns one Hive object.
     * */
    public static Hive get( UserContext userContext, DataSource dataSource )
    {
        synchronized( controllers )
        {
            if( controllers.get( userContext ) == null )
            {
                Hive Hive = new Hive( userContext, dataSource );
                controllers.put( userContext.getIdentifier() + dataSource.toString(), Hive );
            }
        }

        return controllers.get( userContext.getIdentifier() + dataSource.toString() );
    }

    /**
     * At present, <strong>create table</strong> seems like not taking too much time, so, I haven't
     * taken that using <code>Thread</code> pool to execute creation job into considering.
     * */
    public void doCreate( String tableName ) throws SQLException, IOException
    {
        Schema schema = dataSource.loadSchema();
        Table table = schema.getTables().get( tableName );

        HiveShell hiveShell = new HiveShell( dataSource, userContext );
        hiveShell.createTable( table );
    }
    
    /**
     * @throws SQLException 
     * @throws IOException 
     * @see #doCreate(String)
     * */
    public void loadDataIntoHiveTable(String tableName) throws SQLException, IOException{
        Schema schema = dataSource.loadSchema();
        Table table = schema.getTables().get( tableName );

        HiveShell hiveShell = new HiveShell( dataSource, userContext );
        hiveShell.loadDataFromHDFS( table );
    }
}
